package com.tbit.uqbike.webmanager.business.maintain_performance.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tbit.common.constant.PerformanceTypeConstant;
import com.tbit.config.datasource.DataSource;
import com.tbit.uqbike.object.pojo.AccountUser;
import com.tbit.common.entity.view.PageResult;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.service.business.AccountUserService;
import com.tbit.uqbike.webmanager.business.maintain_performance.constant.PerformanceRuleType;
import com.tbit.uqbike.webmanager.business.maintain_performance.dao.log.MovePerformanceDao;
import com.tbit.uqbike.webmanager.business.maintain_performance.object.MovePerformance;
import com.tbit.uqbike.webmanager.business.maintain_performance.object.MovePerformanceLog;
import com.tbit.uqbike.webmanager.business.maintain_performance.object.dto.stat.*;
import com.tbit.uqbike.webmanager.dao.core.AccountUserDao;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 挪车绩效记录服务
 *
 * @author <a href="mailto:zheng.zebiao@tbit.com.cn">zb</a>
 * @since 2025/2/18
 */
@Slf4j
@Service
@AllArgsConstructor
public class MovePerformanceService extends ServiceImpl<MovePerformanceDao, MovePerformance> {
    final AccountUserService accountUserService;
    final AccountUserDao accountUserDao;
    final MovePerformanceLogService performanceLogService;

    /**
     * 分页查询详情
     */
    public PageResult<MovePerformanceDetail> queryDetailPage(MovePerformanceDetailReq req) {
        // 查询绩效分页
        Page<MovePerformanceDetail> details = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        getBaseMapper().queryDetailPage(req);
        details.close();

        Map<Integer, AccountUser> accountUserMap = Optional.ofNullable(accountUserService.getByType(req.getAccountId(), false))
                .map(x -> x.stream().collect(Collectors.toMap(AccountUser::getAccountUserId, Function.identity(), (v1, v2) -> v1)))
                .orElse(Collections.emptyMap());
        if (CollUtil.isNotEmpty(details)) {
            for (MovePerformanceDetail detail : details) {
                // 补充运维人员信息
                AccountUser accountUser = accountUserMap.get(detail.getAccountUserId());
                if (accountUser != null) {
                    detail.setAccountUserName(accountUser.getName());
                    detail.setAccountUserPhone(accountUser.getPhone());
                }
            }
        }

        return PageResult.convertPage(details.toPageInfo());
    }

    /**
     * 查询统计图表
     */
    public List<PerformanceChartPerDateDetail> queryStatChart(Integer accountId, Date startTime, Date endTime, Integer accountUserId, Integer machineType, Integer isValid, LoginInfo loginInfo) {
        List<PerformanceChartDo> chartDos = getBaseMapper().queryPerformanceChart(accountId, startTime, endTime, accountUserId, machineType, isValid);

        List<AccountUser> accountUserList = new ArrayList<>();
        if (accountUserId == null){
            accountUserList.addAll((List<AccountUser>) accountUserService.getParentsAccountUser(accountId, loginInfo).getData());
        }else {
            accountUserList.add(accountUserService.getAccountUserById(accountUserId));
        }
        Map<Integer, String> accountUserMap = Optional.ofNullable(accountUserList)
                .map(x -> x.stream().collect(Collectors.toMap(AccountUser::getAccountUserId, AccountUser::getName, (v1, v2) -> v1)))
                .orElse(Collections.emptyMap());
        return PerformanceChartPerDateDetail.fromDo(accountUserMap, chartDos, LocalDateTimeUtil.of(startTime).toLocalDate(), LocalDateTimeUtil.of(endTime).toLocalDate());
    }

    /**
     * 分页查询概览
     */
    public PageResult<PerformanceOverviewResp> queryOverviewPage(@Valid PerformanceOverviewReq req) {
        try (Page<PerformanceOverviewResp> page = PageHelper.startPage(req.getPageNo(), req.getPageSize())) {
            getBaseMapper().queryOverviewPage(req);


            // 填充运维人员信息
            Map<Integer, AccountUser> accountUserMap = Optional.ofNullable(accountUserService.getByType(req.getAccountId(), false))
                    .map(x -> x.stream().collect(Collectors.toMap(AccountUser::getAccountUserId, Function.identity(), (v1, v2) -> v1)))
                    .orElse(Collections.emptyMap());
            if (CollUtil.isNotEmpty(page)) {
                for (PerformanceOverviewResp overview : page) {
                    AccountUser accountUser = accountUserMap.get(overview.getAccountUserId());
                    if (accountUser != null) {
                        overview.setAccountUserName(accountUser.getName());
                        overview.setAccountUserPhone(accountUser.getPhone());
                    }
                }
            }
            return PageResult.convertPage(page.toPageInfo());
        }
    }

    /**
     * 更新挪车记录的绩效
     * @param performanceId 绩效记录id
     * @param performance 绩效值
     * @param remark 备注
     */
    @DS(DataSource.LOG)
    @Transactional
    public void updatePerformance(Long performanceId, BigDecimal performance, String remark) {
        MovePerformance update = getById(performanceId);
        BigDecimal oldPerformance = update.getPerformance();
        update.setPerformanceId(performanceId);
        update.setPerformance(performance);
        update.setRemark(remark);
        update.setPerformanceDetail("人工修改绩效: 总绩效" + NumberUtil.toStr(performance, true));
        update.setPerformanceType(PerformanceTypeConstant.MANUAL);
        updateById(update);
        // 计算新旧绩效差值，用于新增一条绩效日志记录move_performance_log
        BigDecimal subPerformance = performance.subtract(oldPerformance);
        if (subPerformance.compareTo(BigDecimal.ZERO) == 0) {
            return;
        }
        MovePerformanceLog log = new MovePerformanceLog();
        BeanUtil.copyProperties(update, log, "remark");
        log.setPerformance(subPerformance);
        log.setRuleType(PerformanceRuleType.MANUAL.getValue());
        log.setRemark("MANAGER-人工修改绩效: " + NumberUtil.toStr(oldPerformance, true) + " -> " + NumberUtil.toStr(performance, true));
        performanceLogService.save(log);
    }
}
